package com.leha.forum.lehare.controller;

import com.leha.forum.lehare.entity.Level;
import com.leha.forum.lehare.entity.Permission;
import com.leha.forum.lehare.response.Result;
import com.leha.forum.lehare.service.LevelPermissionService;
import com.leha.forum.lehare.service.LevelService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lovelycat
 * @version 1.0
 * @since 2025-04-28 18:15
 */
@RestController
@RequestMapping("/level-permission")
public class LevelPermissionController {
    @Resource
    private LevelService levelService;
    @Resource
    private LevelPermissionService levelPermissionService;

    @GetMapping("/all")
    public Result<?> getAllLevelPermissions() {
        // 先获取所有等级
        List<Level> allLevels = levelService.getAllLevels();

        // 再获取各个等级已经绑定的权限列表
        Map<Integer, Map<String, Object>> map = new HashMap<>();
        for (Level level : allLevels) {
            Map<String, Object> inner = new HashMap<>();
            inner.put("level", level);
            inner.put("permissions", levelPermissionService.getLevelPermissions(level.getLevelId()));
            map.put(level.getLevelId(), inner);
        }

        return Result.success(map);
    }

    @PostMapping("/bind")
    public Result<?> bind(Integer levelId, Integer permissionId) {
        if (levelPermissionService.bindLevelPermission(levelId, permissionId)) {
            return Result.success("绑定成功");
        } else {
            return Result.failed(500, "绑定失败");
        }
    }

    @PostMapping("/unbind")
    public Result<?> unbind(Integer levelId, Integer permissionId) {
        if (levelPermissionService.unbindLevelPermission(levelId, permissionId)) {
            return Result.success("解绑成功");
        } else {
            return Result.failed(500, "解绑失败");
        }
    }
}
